<?php
// +----------------------------------------------------------------------
// | ZGUAN [ 致力于帮助更多的中小企业物联网转型 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.zguan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ZGUAN 并不是自由软件，未经许可不能去掉ZGUAN 相关版权
// +----------------------------------------------------------------------
// | Author: ZGUAN Team <admin@zguan.cn>  0769-82282996  15899929162
// +----------------------------------------------------------------------
namespace app\common\repositories\repair;

use think\facade\Db;
use think\exception\ValidateException;
use app\common\repositories\BaseRepository;
use app\common\dao\repair\RepairOrderDao;
use app\common\repositories\repair\RepairLogRepository;
use app\common\repositories\property\basic\PropertyBasicRepository;

/**
 * Class RepairOrderRepository
 *
 * @mixin RepairOrderDao
 */
class RepairOrderRepository extends BaseRepository
{

    public function __construct(RepairOrderDao $dao)
    {
        $this->dao = $dao;
    }

    /**
     * @param array $where
     * @param $page
     * @param $limit
     * @return array
     */
    public function getPropertyList(array $where, $page, $limit, int $propertyId = null)
    {
        $query = $this->dao->search($where, $propertyId);
        $count = $query->count();
        $list = $query->page($page, $limit)
            ->with([
                'cateInfo' => function ($query) {
                    $query->bind(['full_cate_name']);
                },
                'propertyInfo' => function ($query) {
                    $query->bind(['property_name' => 'name']);
                }
            ])
            ->order('id', 'desc')
            ->select();
        return compact('list', 'count');
    }


    /**
     * 报修处理
     * @param {Object} int $propertyId
     * @param {Object} array $data
     *
     */
    public function editRepair(int $userId, array $data, int $propertyId)
    {
        /** @var PropertyBasicRepository $propertyRepository */
        $propertyRepository = app()->make(PropertyBasicRepository::class);
        if (!$propertyRepository->propertyExists($propertyId, $data['property_id'])) {
            throw new ValidateException('物业不存在');
        }
        $picture = [];
        if (isset($data['picture'])) {
            $picture = $data['picture'];
            unset($data['picture']);
        }
        $data['property_id'] = $propertyId;
        return Db::transaction(function () use ($userId, $data, $picture, $propertyId) {
            $repairInfo = $this->dao->get($data['repair_id']);
            if (!$repairInfo) {
                throw new ValidateException('数据不存在');
            }
            $param['status'] = $data['is_type'];

            $param['handle_time'] = date('Y-m-d H:i:s');
            $param['handler_user_id'] = $userId;
            $status = 2;
            switch ($data['is_type']) {
                case '3':
                    $status = 9;
                    break;
                case '4':
                    $status = 3;
                    break;
            }

            $this->dao->update($data['repair_id'], $param);
            if ($picture) {
                /** @var RepairPictureRepository $pictureRepository */
                $pictureRepository = app()->make(RepairPictureRepository::class);
                $pictureRepository->delPicture($data['repair_id']);
                $pictureRepository->addRepairPicture($propertyId, $picture, 2);
            }
            /** @var RepairLogRepository $repairLogRepository */
            $repairLogRepository = app()->make(RepairLogRepository::class);
            $repairLogRepository->addLog($propertyId, $repairInfo['id'], $status, $data['remark']);
            return $repairInfo;
        });
    }

    public function addInfo(int $propertyId, array $data, int $userId = 0)
    {
        return Db::transaction(function () use ($data, $propertyId, $userId) {
            $data['property_id'] = $propertyId;
            $data['user_id'] = $userId;
            $picture = [];
            if (isset($data['picture'])) {
                $picture = $data['picture'];
            };
            unset($data['picture']);
            $dataInfo = $this->dao->create($data);
            if ($picture) {
                /** @var RepairPictureRepository $pictureRepository */
                $pictureRepository = app()->make(RepairPictureRepository::class);
                $pictureRepository->addRepairPicture($dataInfo['id'], $picture, 1);
            }

            return $dataInfo;
        });
    }

    public function editInfo($info, array $data, int $userId = 0)
    {
        return Db::transaction(function () use ($data, $info, $userId) {
            $picture = null;
            $resPicture = false;
            if (isset($data['picture'])) {
                $picture = $data['picture'];
                $resPicture = true;
            }
            unset($data['picture']);
            if ($picture !== null) {
                /** @var RepairPictureRepository $pictureRepository */
                $pictureRepository = app()->make(RepairPictureRepository::class);
                $pictureRepository->clearRepairPicture($info['id'], 1);
                $resPicture = $pictureRepository->addRepairPicture($info['id'], $picture, 1);
            }
            $res = $this->dao->update($info['id'], $data);

            return ($res || $resPicture);
        });
    }


    public function allotInfo($info, array $data, int $userId = 0)
    {
        return Db::transaction(function () use ($data, $info, $userId) {
            $remark = $data['remark'];
            $data['status'] = 2;
            unset($data['id']);
            unset($data['remark']);
            $res = $this->dao->update($info['id'], $data);
            if ($res) {
                event('maintain.repair.allot', [
                    'maintainInfo' => $info,
                    'remark' => $remark,
                    'userId' => $userId
                ]);
            }
            return $res;
        });
    }

    public function cancellnfo($info, array $data, int $userId = 0)
    {
        return Db::transaction(function () use ($data, $info, $userId) {
            $remark = $data['cancel_remark'];
            $data['status'] = 4;
            unset($data['id']);
            unset($data['cancel_remark']);
            $res = $this->dao->update($info['id'], $data);
            if ($res) {
                event('maintain.repair.cancel', [
                    'maintainInfo' => $info,
                    'remark' => $remark,
                    'userId' => $userId
                ]);
            }
            return $res;
        });
    }

    public function handlelnfo($info, array $data, int $userId = 0)
    {
        return Db::transaction(function () use ($data, $info, $userId) {
            $remark = $data['remark'];
            $data['status'] = 3;
            unset($data['id']);
            unset($data['remark']);
            $picture = [];
            if (isset($data['picture'])) {
                $picture = $data['picture'];
            };
            unset($data['picture']);
            if ($picture) {
                /** @var RepairPictureRepository $pictureRepository */
                $pictureRepository = app()->make(RepairPictureRepository::class);
                $pictureRepository->addRepairPicture($info['id'], $picture, 2);
            }
            $res = $this->dao->update($info['id'], $data);
            if ($res) {
                event('maintain.repair.handle', [
                    'info' => $info,
                    'remark' => $remark,
                    'userId' => $userId
                ]);
            }
            return $res;
        });
    }


    public function getDetail(int $id)
    {
        return $this->dao->getSearch(['id' => $id])
            ->find();
    }


    /**
     * 批量删除
     * @param array $ids
     * @return array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function batchDelete(array $ids, int $userId = 0)
    {
        $list = $this->dao->selectWhere([
            ['id', 'in', $ids]
        ]);
        if ($list) {
            foreach ($list as $k => $v) {
                $this->deleteInfo($v, $userId);
            }
            return $list;
        }
        return [];
    }

    public function deleteInfo($info, int $userId = 0)
    {
        return Db::transaction(function () use ($info, $userId) {
            /** @var RepairLogRepository $repairLogRepository */
            $repairLogRepository = app()->make(RepairLogRepository::class);
            // 清除报修日志
            $repairLogRepository->clearRepairLog($info['id']);
            /** @var RepairPictureRepository $pictureRepository */
            $pictureRepository = app()->make(RepairPictureRepository::class);
            // 清除报修图片
            $pictureRepository->clearRepairPicture($info['id'], 1);
            $pictureRepository->clearRepairPicture($info['id'], 2);
            event('maintain.repair.cancel', [
                'info' => $info,
                'userId' => $userId
            ]);
            return $this->dao->delete($info['id']);
        });
    }

    /**
     * 报修取消
     * @param int $userId
     * @param array $data
     * @param int|null $propertyId
     * @return mixed
     */
    public function cancelRepair(int $userId, array $data, int $propertyId = null)
    {
        if (empty($data['cancel_remark'])) {
            throw new ValidateException('请输入取消说明');
        }
        return Db::transaction(function () use ($data, $userId, $propertyId) {
            $repairInfo = $this->dao->get($data['repair_id']);
            if (!$repairInfo) {
                throw new ValidateException('数据不存在');
            }
            if ($repairInfo['user_id'] != $userId) {
                throw new ValidateException('非法操作');
            }
            if ($repairInfo['status'] != 4) {
                $data['status'] = 4;
                unset($data['repair_id']);
                $res = $this->dao->update($repairInfo['id'], $data);
                /** @var RepairLogRepository $repairLogRepository */
                $repairLogRepository = app()->make(RepairLogRepository::class);
                $repairLogRepository->addLog($repairInfo['id'], '取消工单 (' . $data['cancel_remark'] . ')', $propertyId, $userId);
                return $res;
            }
            throw new ValidateException('非法操作');
        });
    }
}
